#include "chatdialog.h"

ChatDialog::ChatDialog(QWidget *parent, in_addr connect_to_ip) :
    QDialog(parent)
{
    memset((void*)&(this->sendMsgTo), 0, sizeof(this->sendMsgTo));
    this->sendMsgTo.sin_family = AF_INET;
    this->sendMsgTo.sin_port = htons(22299);
    this->sendMsgTo.sin_addr = connect_to_ip;
    if(!(this->send_msg_sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)))
        perror("send socket error : ");
    this->chatHistory = new QTextEdit;
    chatHistory->setReadOnly(true);
    //chatHistory->setDisabled(true);
    this->msgInput = new QLineEdit;
    this->mainLayout = new QVBoxLayout;
    mainLayout->addWidget(chatHistory);
    mainLayout->addWidget(msgInput);
    this->setLayout(mainLayout);
    QObject::connect(msgInput, SIGNAL(returnPressed()), this, SLOT(msgEntered()));
    this->show();

}

ChatDialog::~ChatDialog()
{
    for(int i = 0; i < this->sessionList->length(); i++)
    {
        if(((this->sessionList)->at(i)).window == this)
            this->sessionList->removeAt(i);
    }
}

void ChatDialog::msgEntered()
{
    char *entered_msg;
    entered_msg = strdup(this->msgInput->text().toAscii().data());
    fprintf(stdout, "%s", entered_msg);
    this->msgInput->clear();
    if(int bytes = sendto(this->send_msg_sock, entered_msg, strlen(entered_msg), 0, (sockaddr*)&(this->sendMsgTo), sizeof(this->sendMsgTo)))
        fprintf(stdout, "%d bytes sent", bytes);
    QString enteredMsg(entered_msg);
    QString you("\nYou : ");
    enteredMsg = you + enteredMsg;
    this->chatHistory->append(enteredMsg);
}
